package com.itheima.prize.api.action;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.prize.commons.db.entity.CardUser;
import com.itheima.prize.commons.db.service.CardUserService;
import com.itheima.prize.commons.utils.ApiResult;
import com.itheima.prize.commons.utils.PasswordUtil;
import com.itheima.prize.commons.utils.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import static com.itheima.prize.commons.config.RedisKeys.USERLOGINTIMES;
@Slf4j
@RestController
@RequestMapping(value = "/api")
@Api(tags = {"登录模块"})
public class LoginController {
    @Autowired
    private CardUserService userService;

    @Autowired
    private RedisUtil redisUtil;

    @PostMapping("/login")
    @ApiOperation(value = "登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name="account",value = "用户名",required = true),
            @ApiImplicitParam(name="password",value = "密码",required = true)
    })
    public ApiResult login(HttpServletRequest request, @RequestParam String account, @RequestParam String password) {
        //TODO：任务3.1-登录模块-用户登录
        //判断账号是否禁用
        String key = USERLOGINTIMES+account;
        //获取过期时间
        long expireTime = redisUtil.getExpire(key);
        if(expireTime>0){
           return  new ApiResult<>(0,"密码错误5次，请5分钟后再登录",null);
        }
        //查询数据库得到用户信息
        CardUser user =  userService.getOne(new QueryWrapper<CardUser>().eq("uname", account).eq("passwd", PasswordUtil.encodePassword(password)));


        //登录失败
        if(user == null) {
            //1.2redis记录登录失败次数
            long count = redisUtil.incr(key, 1);
            if(count == 5){
                redisUtil.expire(key,300);
            }
            //1.3封装返回数据
            return  new ApiResult<>(0,"账户名或密码错误",null);

        }
        //2登录成功
        //2.1设置用户session
        //2.2用户信息脱敏
        user.setPasswd(null);
        user.setIdcard(null);
        request.getSession().setAttribute("user", user);
        //清除失败次数
        redisUtil.del(key);
        //2.3返回登录成功信息
        return new ApiResult<>(1,"登录成功",user);
    }

    @GetMapping("/logout")
    @ApiOperation(value = "退出")
    public ApiResult logout(HttpServletRequest request) {
        //TODO：任务3.2-登录模块-用户退出
        HttpSession session = request.getSession();
        if(session!=null){
            session.invalidate();
        }
        return new ApiResult<>(1,"退出成功",null);
    }

}